package com.hengda.museumonline.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.VisibleRegion;
import com.amap.api.services.cloud.CloudItem;
import com.amap.api.services.cloud.CloudItemDetail;
import com.amap.api.services.cloud.CloudResult;
import com.amap.api.services.cloud.CloudSearch;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hengda.museumonline.MyApplication;
import com.hengda.museumonline.R;
import com.hengda.museumonline.adapter.FindAdapter;
import com.hengda.museumonline.adapter.LeaningAdapter;
import com.hengda.museumonline.entity.LeaningBean;
import com.hengda.museumonline.entity.LoginBean;
import com.hengda.museumonline.http.CallServer;
import com.hengda.museumonline.ui.CityChengeActivity;
import com.hengda.museumonline.ui.MainActivity;
import com.hengda.museumonline.ui.SettingActivity;
import com.hengda.museumonline.utils.CityChengeUtil;
import com.hengda.museumonline.utils.GlideCircleTransform;
import com.hengda.museumonline.utils.TabIconsUtil;
import com.hengda.museumonline.utils.ToastUtil;
import com.litesuits.common.utils.PackageUtil;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.yolanda.nohttp.NoHttp.getContext;

/**
 * Created by Administrator on 2016/10/5.
 */

public class ArchPager {
    private static final String TAG = "ArchPager";
    public MainActivity mainActivity;
    public Bundle savedInstanceState;
    public View view;
    private LinearLayout llCityChenge;
    private RecyclerView recyclerView;
    private TabLayout tabs;
    public ImageView ivMap;
    private AMap aMap;
    private UiSettings mUiSettings;
    public boolean temp = true;
    private TextureMapView textureMapView;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private CloudSearch mCloudSearch;
    private List<CloudItem> mCloudItems;
    private ArrayList<Marker> markers = new ArrayList<>();
    private LatLngBounds latLngBounds;
    private String url;
    private ImageView imageView;
    private double limit = 0.02;
    public PopupWindow mPopWindow;
    private String[] titles = {"发现", "学术"};
    private int[] tabIcons = {
            R.drawable.arch_find2,
            R.drawable.arch_leaning2};
    private int[] tabIconsPressed = {
            R.drawable.arch_find1,
            R.drawable.arch_leaning1};
    private CityChengeUtil util;
    private ImageView location;
    private PopupWindow mPop;
    private LeaningBean leaningBean;

    public ArchPager(MainActivity mActivity, Bundle savedInstanceState) {
        this.mainActivity = mActivity;
        this.savedInstanceState = savedInstanceState;
        initView();
    }

    public void initView() {
        view = View.inflate(mainActivity, R.layout.archpager, null);
        util = new CityChengeUtil();
        llCityChenge = (LinearLayout) view.findViewById(R.id.ll_city_chenge);
        llCityChenge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                util.getCityFromServer(mainActivity, llCityChenge, "archaeol/city");
                ivMap.setImageResource(R.drawable.arch_list);
                mPopWindow.dismiss();
                temp = true;
            }
        });
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        tabs = (TabLayout) view.findViewById(R.id.tabs);
        tabs.addTab(tabs.newTab().setTag(0));
        tabs.addTab(tabs.newTab().setTag(1));
        tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabs.setSelectedTabIndicatorColor(mainActivity.getResources().getColor(R.color.refresh_bg));
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int i = (int) tab.getTag();
                if (0 == i) {
                    llCityChenge.setVisibility(View.VISIBLE);
                    ivMap.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.INVISIBLE);
                } else {
                    llCityChenge.setVisibility(View.INVISIBLE);
                    ivMap.setVisibility(View.INVISIBLE);
                    recyclerView.setVisibility(View.VISIBLE);
                    getLeaningFromNet(2, recyclerView);
                    if (mPopWindow != null && mPopWindow.isShowing()) {
                        mPopWindow.dismiss();
                        ivMap.setImageResource(R.drawable.arch_list);
                        temp = !temp;
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        TabIconsUtil util = new TabIconsUtil(mainActivity, tabs, titles, tabIcons, tabIconsPressed);
        util.setTabIcons2();
        ivMap = (ImageView) view.findViewById(R.id.iv_map);
        getPopup();
        ivMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (temp) {
                    ivMap.setImageResource(R.drawable.arch_map);
                    mPopWindow.showAsDropDown(ivMap, 0, 20);
                } else {
                    ivMap.setImageResource(R.drawable.arch_list);
                    mPopWindow.dismiss();
                }
                temp = !temp;
            }
        });
        textureMapView = (TextureMapView) view.findViewById(R.id.map);
        textureMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = textureMapView.getMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);
            setUpMap();
            getData();
            searchByBound();
        }
        location = (ImageView) view.findViewById(R.id.location);
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final LatLng latLng = new LatLng(aMap.getMyLocation().getLatitude(), aMap.getMyLocation().getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            }
        });
    }

    private void getLeaningFromNet(int i, final RecyclerView recyclerView) {
        Request request = NoHttp.createStringRequest(MyApplication.url + "archaeol/expertpoint", RequestMethod.GET);
        request.add("p", "a");
        request.add("v", PackageUtil.getAppPackageInfo(mainActivity).versionName);
        request.add("pid", i);

        CallServer.getRequestInstance().add(mainActivity, i, request, new OnResponseListener() {
            @Override
            public void onStart(int what) {
            }

            @Override
            public void onSucceed(int what, Response response) {
                System.out.println("response:" + response.get().toString());
                if (200 == response.getHeaders().getResponseCode()) {
                    Gson gson = new Gson();
                    leaningBean = gson.fromJson(response.get().toString(), LeaningBean.class);
                    if (leaningBean != null && leaningBean.getData() != null && leaningBean.getData().size() > 0) {
                        if (what == 0) {
                            recyclerView.setAdapter(new FindAdapter(getContext(), leaningBean));
                        } else if (what == 2) {
                            recyclerView.setAdapter(new LeaningAdapter(getContext(), leaningBean));
                        }

                    }
                }

            }

            @Override
            public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
                System.out.println("onFailed:" + exception);
            }

            @Override
            public void onFinish(int what) {
            }
        });
    }


    private void getPopup() {
        View contentView = LayoutInflater.from(mainActivity).inflate(R.layout.popup_list, null);
        RecyclerView rView = (RecyclerView) contentView.findViewById(R.id.recyclerview);
        rView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
        getLeaningFromNet(0, rView);
        mPopWindow = new PopupWindow(contentView);
        mPopWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        mPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(new LocationSource() {
            @Override
            public void activate(OnLocationChangedListener onLocationChangedListener) {
                mListener = onLocationChangedListener;
                if (mlocationClient == null) {
                    mlocationClient = new AMapLocationClient(getContext());
                    mLocationOption = new AMapLocationClientOption();
                    //设置为高精度定位模式
                    mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                    //设置定位参数
                    mlocationClient.setLocationOption(mLocationOption);
                    // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
                    // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
                    // 在定位结束后，在合适的生命周期调用onDestroy()方法
                    // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
                    //设置定位监听
                    mlocationClient.setLocationListener(new AMapLocationListener() {
                        @Override
                        public void onLocationChanged(AMapLocation amapLocation) {
                            if (mListener != null && amapLocation != null) {
                                if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                                    mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                                    System.out.println("经纬度：" + amapLocation.getLatitude() + ":" + amapLocation.getLongitude());
                                } else {
                                    String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                                }
                            }
                        }
                    });
                    mlocationClient.startLocation();
                }
            }

            @Override
            public void deactivate() {
                mListener = null;
                if (mlocationClient != null) {
                    mlocationClient.stopLocation();
                    mlocationClient.onDestroy();
                }
                mlocationClient = null;
            }
        });// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    private void getData() {
//        mCloudSearch = new CloudSearch(getContext());
//        mCloudSearch.setOnCloudSearchListener(
//                new CloudSearch.OnCloudSearchListener() {
//                    @Override
//                    public void onCloudSearched(CloudResult result, int rCode) {
//                        if (rCode == 1000) {
//                            if (result != null && result.getQuery() != null) {
//                                if (result.getQuery().equals(mQuery)) {
//                                    mCloudItems = result.getClouds();
//                                    if (mCloudItems != null && mCloudItems.size() > 0) {
//                                        //  aMap.clear();
//                                        for (CloudItem item : mCloudItems) {
//                                            if (aMap.getMapScreenMarkers().isEmpty()) {
//                                                // items.add(item);
//                                                addMarker(item);
//                                            } else {
//                                                if (isAddMarker(item)) {
//                                                    // items.add(item);
//                                                    addMarker(item);
//                                                }
//                                            }
//                                        }
//                                        System.out.println("数量：" + aMap.getMapScreenMarkers().size());
//                                    } else {
//
//                                    }
//                                }
//                            } else {
//                                ToastUtil.show(getContext(), "没有搜索到相关数据！");
//                            }
//                        } else
//
//                        {
//                            ToastUtil.showerror(getContext(), rCode);
//                        }
//                    }
//
//                    @Override
//                    public void onCloudItemDetailSearched(CloudItemDetail item, int rCode) {
//                    }
//                }
//
//        );
    }

    private void removeMarker(List<Marker> mapScreenMarkers) {
        for (int i = 0; i < mapScreenMarkers.size(); i++) {
            for (int j = i + 1; i < mapScreenMarkers.size(); i++) {
                double distance = getDistanceBetweenTwoPoints(toScreenLocation1(mapScreenMarkers.get(i)).x,
                        toScreenLocation1(mapScreenMarkers.get(i)).y,
                        toScreenLocation1(mapScreenMarkers.get(j)).x,
                        toScreenLocation1(mapScreenMarkers.get(j)).y);
                if (distance < 160) {
                    mapScreenMarkers.get(i).remove();
                }
            }
        }
    }

    private void addMarker(CloudItem c) {
        url = c.getCustomfield().get("images_url");
        View markerView = View.inflate(getContext(), R.layout.marker, null);
        imageView = (ImageView) markerView.findViewById(R.id.iv_image);
        Glide.with(getContext()).load("http://www.wenbozaixian.com" + url).transform(new GlideCircleTransform(getContext())).into(imageView);

        Marker marker = aMap.addMarker(new MarkerOptions().title(c.getTitle()).snippet(c.getSnippet())
                .position(new LatLng(c.getLatLonPoint().getLatitude(), c.getLatLonPoint().getLongitude()))
                .icon(BitmapDescriptorFactory.fromView(markerView)));
        markers.add(marker);

        Log.d(TAG, "_id" + c.getID());
        Log.d(TAG, "_location" + c.getLatLonPoint().toString());
        Log.d(TAG, "_cloudImage" + c.getCloudImage());
        Log.d(TAG, "_name" + c.getTitle());
        Log.d(TAG, "_address" + c.getSnippet());
        Log.d(TAG, "_caretetime" + c.getCreatetime());
        Log.d(TAG, "_updatetime" + c.getUpdatetime());
        Log.d(TAG, "_distance" + c.getDistance());
        Iterator iter = c.getCustomfield().entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            Log.d(TAG, key + "   " + val);
        }
    }

    private boolean isAddMarker(CloudItem c) {
        for (Marker m : aMap.getMapScreenMarkers()) {
            double distance = getDistanceBetweenTwoPoints(toScreenLocation1(m).x, toScreenLocation1(m).y,
                    toScreenLocation(c).x, toScreenLocation(c).y);
            if (distance < 160) {
                return false;
            }
        }
        return true;
    }


    /**
     * 两点的距离
     *
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @return
     */
    private double getDistanceBetweenTwoPoints(double x1, double y1, double x2,
                                               double y2) {
        double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
                * (y1 - y2));
        return distance;
    }

    /**
     * 经纬度转像素
     */
    private Point toScreenLocation(CloudItem item) {
        LatLng mLatlng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
        return aMap.getProjection().toScreenLocation(mLatlng);

    }

    /**
     * 经纬度转像素
     */
    private Point toScreenLocation1(Marker item) {
        return aMap.getProjection().toScreenLocation(item.getPosition());

    }

    boolean b;

    public void searchByBound() {
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                if (cameraPosition.zoom >= 13.01) {
                    mUiSettings.setZoomGesturesEnabled(false);
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(13));
                }
                if (cameraPosition.zoom <= 13) {
                    mUiSettings.setZoomGesturesEnabled(true);
                }

                System.out.println("ZoomPosition:" + cameraPosition.zoom);
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (aMap.getMapScreenMarkers().size() > 1) {
                    removeMarker(aMap.getMapScreenMarkers());
                }

                VisibleRegion visibleRegion = aMap.getProjection().getVisibleRegion(); // 获取可视区域、
                latLngBounds = visibleRegion.latLngBounds;
                for (Marker m : markers) {
                    if (!latLngBounds.contains(m.getPosition())) {
                        m.remove();
                    }
                }

                float distance = AMapUtils.calculateLineDistance(cameraPosition.target, latLngBounds.northeast);
                System.out.println("distance:" + distance);
                getTagfromNet(cameraPosition, distance);
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                getExhibition();
                marker.showInfoWindow();
                return false;
            }
        });
    }

    private void getTagfromNet(CameraPosition cameraPosition, float distance) {
        System.out.println("经纬度：" + (int) cameraPosition.target.longitude + ":" + (int) cameraPosition.target.latitude + ",,distance:" + (int) distance);
        Request request = NoHttp.createStringRequest(MyApplication.url + "archaeol/tag", RequestMethod.GET);
        request.add("p", "a");
        request.add("v", PackageUtil.getAppPackageInfo(mainActivity).versionName);
        request.add("x", (int) cameraPosition.target.longitude);
        request.add("y", (int) cameraPosition.target.latitude);
        request.add("r", (int) distance);

        CallServer.getRequestInstance().add(mainActivity, 0, request, new OnResponseListener() {
            @Override
            public void onStart(int what) {
            }

            @Override
            public void onSucceed(int what, Response response) {
                System.out.println("response:" + response.get().toString());
                if (200 == response.getHeaders().getResponseCode()) {
                    Gson gson = new Gson();
                }

            }

            @Override
            public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
                System.out.println("onFailed:" + exception);
            }

            @Override
            public void onFinish(int what) {
            }
        });
    }

    private void getExhibition() {
        if (mPop != null && mPop.isShowing()) {
            mPop.dismiss();
        }
        View contentView = LayoutInflater.from(mainActivity).inflate(R.layout.exhibition1_pop, null);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPop.dismiss();
            }
        });
        mPop = new PopupWindow(contentView);
        mPop.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPop.setBackgroundDrawable(new BitmapDrawable());
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(view, Gravity.BOTTOM, 0, 220);
    }

    public void initData() {

    }
}
